from PyQt5.QtCore import pyqtSignal, QObject, pyqtSlot
from src.utils.crawler import fetch_all_servants


class ServantLoaderWorker(QObject):
    servants_updated = pyqtSignal(object)
    log_signal = pyqtSignal(str)
    finished = pyqtSignal()

    def __init__(self):
        super().__init__()
        print("ServantLoaderWorker initialized")

    @pyqtSlot()
    def start(self):
        # 不再嵌套 Python 线程；直接在此 QThread 中执行阻塞 I/O
        try:
            self.log_signal.emit("[INFO] 正在后台加载从者信息...")

            def on_page(servants):
                self.log_signal.emit(f"[INFO] 已加载 {len(servants)} 个从者...")
                self.servants_updated.emit(servants)

            def on_finish(all_servants):
                self.log_signal.emit(f"[INFO] 全部加载完成：{len(all_servants)} 个从者")
                self.finished.emit()

            fetch_all_servants(on_page_fetched=on_page, on_finished=on_finish)
        except Exception as e:
            self.log_signal.emit(f"[ERROR] 加载从者失败: {e}")
            self.servants_updated.emit([])
            self.finished.emit()

            def on_finish(all_servants):
                self.log_signal.emit(f"[INFO] 全部加载完成：{len(all_servants)} 个从者")
                self.finished.emit()

            # 现在 fetch_all_servants 在一个非GUI、非QThread事件循环的线程中运行
            fetch_all_servants(on_page_fetched=on_page, on_finished=on_finish)
        except Exception as e:
            self.log_signal.emit(f"[ERROR] 加载从者失败: {e}")
            self.servants_updated.emit([])  # 发送空列表以清空或显示错误状态
            self.finished.emit()
